from urllib import request
from urllib import error
from urllib import parse
from http import cookiejar

if __name__ == '__main__':
    #登陆地址
    login_url = 'http://dataqjr.tools.vipshop.com/account/getUserInfo'    
    #User-Agent信息                   
    user_agent = r'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
    #Headers信息
    head = {'User-Agnet': user_agent, 'Connection': 'keep-alive','X-Requested-With':'XMLHttpRequest','redirect_url':'http://dataqjr.tools.vipshop.com/html_hive/hiveData.html?uid=undefined&num=0.5926007101143651'}
    #登陆Form_Data信息
    Login_Data = {}
    Login_Data['num'] = '0.03164791947252299'
    logingpostdata = parse.urlencode(Login_Data).encode('utf-8')
    #声明一个CookieJar对象实例来保存cookie
    cookie = cookiejar.CookieJar()
    #利用urllib.request库的HTTPCookieProcessor对象来创建cookie处理器,也就CookieHandler
    cookie_support = request.HTTPCookieProcessor(cookie)
    #通过CookieHandler创建opener
    opener = request.build_opener(cookie_support)
    #创建Request对象
    requestLogin = request.Request(url=login_url, data=logingpostdata, headers=head)

    #面向对象地址
    date_url = 'http://dataqjr.tools.vipshop.com/query/mysql'
    #面向对象
    Date_Data = {}
    Date_Data['id'] = '7701'
    Date_Data['hiveSql'] = 'select * from act_evt_log\n\r'
    Date_Data['db_name'] = 'vip_aml_activiti'
    Date_Data['select_db'] = '0'
    Date_Data['cas_info[0]']='cai.tian'
    Date_Data['cas_info[1]']='cai.tian@vipshop.com'
    Date_Data['cas_info[2]']='20161101103559'
    #使用urlencode方法转换标准格式
    datepostdata = parse.urlencode(Date_Data).encode('utf-8')
    print(datepostdata)
    req2 = request.Request(url=date_url, data=datepostdata, headers=head)
    try:
        #使用自己创建的opener的open方法
        print('调用登录')
        responseLogin = opener.open(requestLogin)
        res = responseLogin.read()
        print(res)
        print('调用数据')
        response2 = opener.open(req2)
        print(responseLogin)
        html = response2.read().decode('utf-8')
        #打印查询结果
        print('返回值'+html)
    except error.URLError as e:
        if hasattr(e, 'code'):
            print(e)
            print("HTTPError:%d" % e.code)
        elif hasattr(e, 'reason'):
            print(e)
            print("URLError:%s" % e.reason)